<template>
  <div id="nearby">
    <van-search
        v-model="searchKeyWord"
        shape="round"
        background="#00bef8"
        show-action
        placeholder="搜索"
        @search="onSearch"
    >
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>
    <van-tabs v-model:active="activeName" @change="onTabChange" style="margin-bottom: 5px">
      <van-tab title="用户" name="nearby"></van-tab>
      <van-tab title="分享" name="share"></van-tab>
    </van-tabs>

    <van-floating-bubble
        v-if="activeName === 'share'"
        axis="xy"
        icon="plus"
        magnetic="x"
        v-model:offset="floatBubbleOffset"
        @click="doCreateBlog"
    />
<!--    用户页-->
    <div v-if="activeName === 'nearby'" class="scroll-container" @scroll="handleScroll">
      <van-card
          v-for="user in nearbyUserList"
          :desc="`个人简介： ${user.profile}`"
          :title="user.username"
          :thumb="user.avatarUrl"
      >
        <template #tags>
          <van-tag v-for="tag in JSON.parse(user.tags)" plain type="primary" style="margin-right: 8px; margin-top: 8px">
            {{ tag }}
          </van-tag>
        </template>
        <template #bottom>
          <div>
            {{ `距离你: ${user.distance >= 1000 ? (user.distance / 1000).toFixed(1) + ' km' : (user.distance).toFixed(2) + 'm'}` }}
          </div>
        </template>
        <template #footer>
          <van-button plain hairline icon="https://fastly.jsdelivr.net/npm/@vant/assets/user-active.png" type="primary"
                      @click="doChat(user.id, user.username)" size="small">私聊我
          </van-button>
        </template>
      </van-card>
      <van-empty v-if="!nearbyUserList || nearbyUserList.length < 1" image="search" description="暂无附近"/>
      <van-loading v-if="isLoading" color="#0094ff" size="24px">加载中...</van-loading>
    </div>
    <!--    分享页-->
    <div class="scroll-container" v-else>
      <div class="blog-list"  @scroll="onScroll">
        <div class="blog-box" v-for="hotBlog in hotBlogList" :key="hotBlog.id">
          <div class="blog-img" @click="toBlogDetail(hotBlog.id)"><img :src="hotBlog.imageUrl" alt=""></div>
          <div class="blog-title">{{ hotBlog.title.length > 8 ? hotBlog.title.substring(0,8) + "……" : hotBlog.title }}</div>
          <div class="blog-foot">
            <div class="blog-user-icon"><img :src="hotBlog.avatarUrl || 'http://img2.baidu.com/it/u=1217440372,1279017633&fm=253&app=138&f=JPEG?w=800&h=800'" alt=""></div>
            <div class="blog-user-name">{{ hotBlog.username }}</div>
            <div class="blog-liked" @click="addLike(hotBlog)" style="font-size: 14px">
              <van-icon :color="hotBlog.isLike ? 'red' : ''" name="good-job-o" size="20"/>{{hotBlog.liked}}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import request from "../../plugins/request.ts";
import {useUserStore} from "../../stores";

const router = useRouter()
const userStore = useUserStore();
// 浮动气泡偏移量设置
const floatBubbleOffset = ref({ x: 300, y: 540})
const pageNum = ref(1);
const isLoading = ref(false)
const activeName = ref('nearby');
const hotBlogList = ref([])
const doChat = (userId: number, username: string) => {
  router.push({
    path: "/chat",
    query: {
      userId: userId,
      username: username
    }
  })
}
/**
 * 跳转到新建blog页面
 */
const doCreateBlog = () => {
  router.push({
    path: "/nearby/blog/add",
  })
}
/**
 * 跳转到博客详情页面
 */
const toBlogDetail = (blogId: number) => {
  router.push({
    path: "/nearby/blog/detail",
    query: {
      blogId
    }
  })
}
const nearbyUserList = ref([]);
// 页面加载时，向后端请求数据
onMounted(() => {
  isLoading.value = true
  getNearbyUserList()
  isLoading.value = false
})
/**
 * 加载附近用户的方法
 */
const getNearbyUserList = async () => {
  pageNum.value = 1
  const result = await request.get("/user/select/nearby", {
    params: {
      "current": pageNum.value,
      "x": userStore.currentLoginUserInfo?.x,
      "y": userStore.currentLoginUserInfo?.y
    }
  })
  if (result?.data.code === 200 && result.data.data) {
    nearbyUserList.value = result.data.data;
  } else {
    showFailToast('加载失败，请刷新重试' + result.data.description);
  }
}

/**
 * 加载热门笔记
 */
const queryHotBlogList = async () => {
  pageNum.value = 1
  const result = await request.get("/blog/hot", {
    params: {
      current: pageNum.value
    }
  })
  if (result.data.code === 200 && result.data.data) {
    hotBlogList.value = result.data.data
  }
}
/**
 * 查询当前用户是否点赞，还有blog完整信息
 */
const queryBlogById = async (blog) => {
  const result = await request.get("/blog/" + blog.id)
  if (result.data.code === 200 && result.data.data) {
    blog.liked = result.data.data.liked
    blog.isLike = result.data.data.isLike
  } else {
    showFailToast(result.data.data.description)
    blog.liked++
  }
}
/**
 * 添加喜欢（点赞）事件
 */
const addLike = async (blog) => {
  const result = await request.put("/blog/like/" + blog.id)
  if (result.data.code === 200 && result.data.data) {
    // 点赞成功就重新查询被点赞的blog
    await queryBlogById(blog)
  } else {
    showFailToast(result.data.data.description)
  }
}

const searchKeyWord = ref('');
const onSearch = () => {
  showToast({
    message: '当前页的搜索框暂未想到功能',
    icon: 'like-o',
  });
};
const onClickButton = () => {
  showToast({
    message: '当前页的搜索框暂未想到功能',
    icon: 'like-o',
  });
}
const onTabChange = async () => {
  //每次进行tab栏的切换时，先给临时变量赋值
  if ( activeName.value === "nearby") {
    isLoading.value = true
    await getNearbyUserList()
    isLoading.value = false
  } else {
    isLoading.value = true
    await queryHotBlogList()
    isLoading.value = false
  }
}

/**
 * 实现附近页面滚动分页
 */
async function handleScroll(event: Event) {
  const {target} = event;
  const scrollContainer = target as HTMLElement;
  if (scrollContainer) {
    const {scrollTop, scrollHeight, clientHeight} = scrollContainer;
    if (scrollTop + clientHeight >= scrollHeight) { // 到达底部时加载更多
      pageNum.value++
      // 加载数据的函数
      const result = await request.get("/user/select/nearby", {
        params: {
          "current": pageNum.value,
          "x": userStore.currentLoginUserInfo?.x,
          "y": userStore.currentLoginUserInfo?.y
        }
      })
      if (result?.data.code === 200 && result.data.data) {
        nearbyUserList.value.push(...result.data.data);
      }
    }
  }
}
/**
 * 实现分享页面滚动分页
 */
let flag = false;
async function onScroll(event: Event) {
  const {target} = event;
  const scrollContainer = target as HTMLElement;
  if (scrollContainer && !flag) { //检查是否在加载中
    const {scrollTop, scrollHeight, clientHeight} = scrollContainer;
    if (scrollTop + clientHeight + 1 >= scrollHeight) { // 到达底部时加载更多
      flag = true;
      pageNum.value++
      try {
        // 加载数据的函数
        const result = await request.get("/blog/hot", {
          params: {
            current: pageNum.value
          }
        })
        if (result.data.code === 200 && result.data.data) {
          hotBlogList.value.push(...result.data.data)
        }
      } catch (error) {
        console.log('error===', error)
      } finally {
        flag = false
      }
    }
  }
}
</script>

<style scoped>
.scroll-container {
  height: 460px; /* 或根据需要调整 */
  overflow-y: auto;
}

.blog-list {
  background-color: #eee;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  height: 100%;
  overflow-y: auto;
}

.blog-box {
  width: 48%;
  background-color: #fff;
  margin: 5px 0;
  box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.blog-img img {
  width: 100%;
  border-radius: 3px;
}

.blog-title {
  padding: 2px 10px;
  height: 20px;
  width: 92%;
  overflow: hidden;
}

.blog-foot {
  display: flex;
  justify-content: space-between;
  margin: 10px 0 5px 0;
  padding: 0 10px;
}

.blog-user-icon {
  width: 10%;
  margin-right: 3px;
}

.blog-user-name {
  width: 65%;
  overflow: hidden;
}

.blog-user-icon img {
  width: 100%;
}

.blog-liked {
  width: 25%;
  display: flex;
  justify-content: flex-end;
}

.blog-liked img {
  width: 30%;
  height: 75%;
  margin-right: 2px;
}
</style>